//
//  BaseNetManager.swift
//  XMLA
//
//  Created by Gao on 17/2/17.
//  Copyright © 2017年 Odm. All rights reserved.
//

import UIKit
import AFNetworking
import MJExtension

// 定义类型
enum ContentType : Int {
    case news
    // 听新闻
    case novels
    // 听小说
    case talkShow
    // 听脱口秀
    case crossTalk
    // 听相声
    case music
    // 听音乐
    case emotion
    // 听情感心声
    case history
    // 听历史
    case lectures
    // 听讲座
    case broadcasr
    // 听广播剧
    case childrenStory
    // 听儿童故事
    case foreignLanguage
    // 听外语
    case game
}


class XMLYNetManager: AFHTTPSessionManager {
    
    /// AFNetworking单例
    static let shared: XMLYNetManager = {
        
        // 实例化对象
        let instance = XMLYNetManager()
        
        // 设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("application/json")
        instance.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
        //申明返回的结果是json类型
        instance.responseSerializer = AFJSONResponseSerializer()
        //申明请求的数据是json类型
        instance.requestSerializer = AFJSONRequestSerializer()
        
        // 返回对象
        return instance
    }()
    
    
    class func GET(url: String, params: [String: Any]?, completed: @escaping (Any?, Error?)->() ) {
        
        shared.get(url, parameters: params, progress: nil, success: { (_, responseObject) in
            completed(responseObject, nil)
        }, failure: { (_, error) in
            completed(nil, error)
            print("GET ERROR: \(error.localizedDescription)")
        })
    }
    
    class func POST(url: String, params: [String: Any]?, completed: @escaping (Any?, Error?)->() ) {
        
        shared.post(url, parameters: params, progress: nil, success: { (_, responseObject) in
            completed(responseObject, nil)
        }, failure: { (_, error) in
            completed(nil, error)
            print("GET ERROR: \(error.localizedDescription)")
        })
    }
    
    
    /**
     *  为了应付某些服务器对于中文字符串不支持的情况，需要转化字符串为带有%号形势
     *
     *  @param path   请求的路径，即 ? 前面部分
     *  @param params 请求的参数，即 ? 号后面部分
     *
     *  @return 转化 路径+参数 拼接出的字符串中的中文为 % 号形势
     */
    class func percentURL(byPath path: String, params: [String: Any]?) -> String {
        
        var percentPath: String = path
        
        if let params = params {
            
            var isFistParam = true
            for (key, value) in params {
                
                if isFistParam == true {
                    percentPath += "?\(key)"
                    percentPath += "=\(value)"
                    isFistParam = false
                }else{
                    percentPath += "&\(key)"
                    percentPath += "=\(value)"
                }
                
            }
        }
        
        //把字符串中的中文转为%号形势
        return percentPath.addingPercentEncoding(withAllowedCharacters: NSCharacterSet(charactersIn:"`#%^{}\"[]|\\<> ").inverted)!
        
        
    }
    
    
    /** 解析,获取内容推荐数据模型 */
    // http://mobile.ximalaya.com/mobile/discovery/v2/category/recommends?categoryId=1&contentType=album&device=android&scale=2&version=4.3.32.2
    class func getContentsFor(forCategoryId categoryID: Int, contentType type: String, completionHandle completed: @escaping (_ responseObject: Any, _ error: Error?) -> Void) -> Any {
        
        let params = ["categoryId": categoryID,
                      "contentType": type,
                      "device":"ios",
                      "scale":2,
                      "version":"4.3.26.2"] as [String : Any]
        
        let kURLPath  = "http://mobile.ximalaya.com/mobile/discovery/v2/category/recommends"
        
        return GET(url: kURLPath, params: params) { (responseObject, error) in
            completed([ContentsModel.mj_object(withKeyValues: responseObject)],error);
            
        }
        
        
    }
    
    
}
